// 统一响应格式中间件

function responseMiddleware(req, res, next) {
  // 统一错误响应：支持 res.error(err) 与 res.error(code, err)
  res.error = function (...args) {
    let status = 500;
    let raw;
    if (typeof args[0] === 'number') {
      status = args[0];
      raw = args[1];
    } else {
      raw = args[0];
    }

    let message = '操作失败！';

    if (raw instanceof Error) {
      message = raw.message || message;
    } else if (typeof raw === 'string') {
      message = raw;
    } else if (raw && typeof raw === 'object') {
      message = raw.message || raw.msg || message;
    }

    const payload = {
      code: status,
      success: false,
      message,
    };
    res.status(status).send(payload);
  };

  res.success = function ({ data = null, msg }) {
    res.status(200).send({ code: 200, success: true, message: msg || '操作成功！', data });
  };

  next();
}

module.exports = responseMiddleware;
